const mongoose = require('mongoose');

const messageSchema = new mongoose.Schema({
  sender: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  // 接收者可以是用户或群组
  receiver: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: false
  },
  // 群组消息的目标群组ID (MySQL中的group ID)
  group_id: {
    type: Number,
    default: null
  },
  // 消息目标类型: 'user' 或 'group'
  target_type: {
    type: String,
    enum: ['user', 'group'],
    default: 'user'
  },
  content: {
    type: String,
    required: true,
    trim: true
  },
  type: {
    type: String,
    enum: ['text', 'image'],
    default: 'text'
  },
  read: {
    type: Boolean,
    default: false
  },
  // 已读的用户ID列表（用于群组消息）
  read_by: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }]
}, {
  timestamps: true
});

// 创建索引以便于快速查询消息
messageSchema.index({ sender: 1, receiver: 1 });
messageSchema.index({ group_id: 1 });
messageSchema.index({ target_type: 1 });

const Message = mongoose.model('Message', messageSchema);

module.exports = Message; 